package com.cn.wanxi.servlet.back.user;

import com.cn.wanxi.dto.UserDto;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/UserRegiterServlet")
public class UserRegiterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        2.获取用户传递过来的值
        String id = req.getParameter("id");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String sessionCode = (String) req.getSession().getAttribute("code");
//        四大作用域
//        1.page 页面对象
//        2.request 请求对象
//        3.session 会话对象
//        4.application  应用程序对象

//        3.将这些值封装到我们的model
        UserDto userDto = new UserDto();
        userDto.setUserModel(new UserModel());
        userDto.getUserModel().setUsername(username);
        userDto.getUserModel().setPassword(password);
        userDto.setCode(code);
        userDto.setSessionCode(sessionCode);

//        4.新建service服务逻辑层，调用
        IUserService iUserService = new UserServiceImpl();
        ResultModel resultModel = new ResultModel();
        if (!"".equals(id)) {
            userDto.getUserModel().setId(Integer.parseInt(id));
            resultModel = iUserService.update(userDto);
        } else {
            resultModel = iUserService.add(userDto);
        }
        JSONArray jsonArray = JSONArray.fromObject(resultModel);
        resp.getWriter().println(jsonArray);
//        req.setAttribute("result", resultModel.getResult());
//        req.getRequestDispatcher("/back/userRegiter.jsp").forward(req, resp);
//        req.setAttribute("result", result);
//        5.返回数据并转发到页面
//        req.getRequestDispatcher("/back/userRegiter.jsp").forward(req, resp);
    }
}
